<template>
  <div class="editor">
    <div class="editor__head">
      <div class="editor__head-title">
        <el-input v-model="title" placeholder="请输入文章标题" show-word-limit type="text" />
      </div>
      <div class="editor__head-right">
        <el-button type="primary" @click="ToDraft" plain>草稿箱</el-button>

        <el-button type="primary" @click="onsubmit">发布</el-button>

        <el-dropdown
          ref="dropdown1"
          trigger="contextmenu"
          style="margin-right: 20px; margin-left: 20px"
        >
          <span class="el-dropdown-link">
            <user-headpic></user-headpic>
          </span>
          <template #dropdown>
            <el-dropdown-menu style="width: 150px">
              <el-dropdown-item>
                <el-icon> <edit-pen /> </el-icon>写文章
              </el-dropdown-item>
              <el-dropdown-item>
                <el-icon> <management /> </el-icon>草稿箱
              </el-dropdown-item>

              <el-dropdown-item divided>
                <el-icon> <user-filled /> </el-icon>我的主页
              </el-dropdown-item>
              <el-dropdown-item>
                <el-icon> <star-filled /> </el-icon>我的收藏
              </el-dropdown-item>
              <el-dropdown-item divided>
                <el-icon> <setting /> </el-icon>个人设置
              </el-dropdown-item>
              <el-dropdown-item divided>
                <el-icon> <switch-button /> </el-icon>退出
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>

      <release
        v-model="isShowRelease"
        :article-summary="articleSummary"
        @submit="submit"
        @submitDraft="submitDraft"
      ></release>
    </div>

    <div class="editor__article">
      <md-editor
        v-model="articleContent"
        editor-class="article-editor"
        :tableShape="[9, 9]"
        placeholder="磨灭你创作的是肮脏不堪的写字台,但让你重新燃起写作的是分享欲。"
        @onSave="onSave"
        @onUploadImg="onUploadImg"
        @onHtmlChanged="onHtmlChanged"
      ></md-editor>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import MdEditor from 'md-editor-v3'
import 'md-editor-v3/lib/style.css'
// :toolbarsExclude="['htmlPreview', 'github', 'fullscreen', 'save', 'revoke', 'next']"
import Release from './components/Release.vue'

import UserHeadpic from '/@/views/User/components/UserHeadpic.vue';

import { imagesUpload } from '../../api/utils/imagesUpload'
import router from '/@/router'

import {
  EditPen,
  Management,
  UserFilled,
  StarFilled,
  Setting,
  SwitchButton
} from '@element-plus/icons-vue'
import { articleAdd, articleAddDraft } from '/@/api/article/articleAdd'

let title = ref('')

let articleContent = ref('')

let articleHtml = ref('')

let articleSummary = ref('')

// 因为需要用到文章摘要，一开始想要使用正则匹配markdown语法,后来发现太复杂了。
// 突然灵机一动匹配html标签内容不更好?
const onHtmlChanged = (h: string) => {
  // console.log(
  //   h
  //     .replace(/<[^>]*>/g, '')
  //     .replace(/\r|\n/gi, '')
  //     .substring(0, 100) as string
  // )  // 贪婪匹配

  articleSummary.value = h
    .match(/[^><]+(?=<\/p>)/g)
    ?.join('')
    .substring(0, 100) as string

  articleHtml.value = h
}

const dropdown1 = ref()
let showClick = () => {
  dropdown1.value.handleOpen()
}

const onSave = () => {
  console.log('保存了')
}

const onUploadImg = (files: FileList, callback: (urls: string[]) => void) => {
  const res: any = Promise.all(
    Array.from(files).map((file) => {
      return new Promise((rev, rej) => {
        const form = new FormData()
        form.append('file', file)

        imagesUpload(form).then((res) => {
          rev(res)
        })
      })
    })
  )

  res.then((res: any) => {
    callback([res[0].data])
  })
}

const onsubmit = () => {
  isShowRelease.value = true
}

const isShowRelease = ref(false)

const submit = (metaData: any) => {
  articleAdd({
    pushDate: Date.parse(String(new Date())),
    modifyDate: Date.parse(String(new Date())),
    userId: localStorage.getItem('userId'),
    title: title.value,
    articleSummary: metaData.articeSummary,
    articleImg: metaData.articleImg,
    categoryId: metaData.category,
    tagId: metaData.tag,
    contentMd: articleContent.value,
    contentHtml: articleHtml.value
  })
    .then((res) => {
      if (res.data) {
        alert('发布成功!')
        router.push('/')
      }
    })
    .catch((res) => {
      alert('发布失败!')
    })
}

const submitDraft = (metaData: any) =>{
  console.log(metaData.category);
    articleAddDraft({
    pushDate: Date.parse(String(new Date())),
    modifyDate: Date.parse(String(new Date())),
    userId: localStorage.getItem('userId'),
    title: title.value,
    articleSummary: metaData.articeSummary,
    articleImg: metaData.articleImg,
    categoryId: metaData.category || 0,
    tagId: metaData.tag || 0,
    contentMd: articleContent.value ?? ' ',
    contentHtml: articleHtml.value ?? ' '
  })
    .then((res) => {
      if (res.data) {
        alert('添加成功!')
        router.push('/')
      }
    })
    .catch((res) => {
      alert('添加失败!')
    })
}

const ToDraft = () =>{
  router.push('/editor/draft')
}
</script>

<style lang="scss" scoped>
:deep(.el-input__inner) {
  height: 60px;
}
.editor {
  width: 100%;

  &__head {
    width: 100%;
    height: 60px;

    display: flex;

    &-title {
      flex: 1 1 auto;
      height: 100%;
      display: flex;
      align-items: center;

      min-width: 300px;
    }

    &-right {
      display: flex;
      align-items: center;
      justify-content: flex-end;

      box-sizing: border-box;

      padding: 0 1.8rem;
    }
  }

  &__article {
    width: 100%;
    height: calc(100vh - 60px);

    .article-editor {
      height: 100%;
      min-width: 584px;
    }
  }
}
</style>
